package com.tanzeer.deliverytracker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.tanzeer.deliverytracker.adapter.ActivesAdapter;
import com.tanzeer.deliverytracker.adapter.CustomListViewAdapter;
import com.tanzeer.deliverytracker.adapter.SpinnerItemAdapter;
import com.tanzeer.deliverytracker.dbhelper.RelsellDBOpenHelper;
import com.tanzeer.deliverytracker.fragments.TrackDetailsFragment;
import com.tanzeer.deliverytracker.models.DelivaryTracks;
import com.tanzeer.deliverytracker.models.RowItem;
import com.tanzeer.deliverytracker.utility.ApplicationVars;
import com.tanzeer.deliverytracker.utility.TrackerServiceClass;

public class DeliveryListActivity extends FragmentActivity implements
		OnItemClickListener,DeliveryListUIUpdaterInterface {
	private ListView listView;
	private SharedPreferences mSharedpreferences;
	ActivesAdapter adapter;
	ArrayList<DelivaryTracks> list;
	ArrayList<DelivaryTracks> adapterList = new ArrayList<DelivaryTracks>();
	ActionBar actionbar;
	ArrayList<String> spinnerItem = new ArrayList<String>();
	String type = "";
	private static final int BUTTON_POSITIVE = -1;
	private static final int BUTTON_NEGATIVE = -2;
	private SearchView mSearchView;

	private LinearLayout mListLayout;
	private FrameLayout mFrameLayout;

	private boolean IsSearchViewOn = false;

	List<RowItem> rowItems;
	ArrayList<RowItem> adapterRow = new ArrayList<RowItem>();
	String track, desc;
	ListView trackListView;
	private String categoryName;
	private TrackDetailsFragment fwb;
	private boolean detailFragmentOpen;
	private CustomListViewAdapter mCustomViewListAdapter;
	private String selectedItemId;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ApplicationVars.getInstance().setDeliveryListCallback(this);
		setContentView(R.layout.activity_deleviry_list);
		actionbar = getActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		trackListView = (ListView) findViewById(R.id.listViewactives);
		mListLayout = (LinearLayout) findViewById(R.id.listcontainer);
		mFrameLayout = (FrameLayout) findViewById(R.id.frameid_container);
		Intent intent = getIntent();
		type = intent.getStringExtra("type");
		categoryName = intent.getStringExtra("categoryName");
		actionbar.setTitle(type);
		if (categoryName != null) {
			actionbar.setTitle(categoryName);
		}
		startProcess(type,true);
	}
	
	
	public void startProcess(final String type,boolean firstCall) {
		if (type.equalsIgnoreCase("Active")) {
			ApplicationVars localObj = ApplicationVars.getInstance();
			if (firstCall) {
			    localObj.setTrackList(new ArrayList<RowItem>());
			}
			ArrayList<RowItem> list = localObj.getTrackList();
			RelsellDBOpenHelper dbHelper = new RelsellDBOpenHelper(this);
			CustomListViewAdapter adapter = null;
			if (dbHelper.checkDBPresence(this)) {
				if(adapterRow != null && rowItems != null) {
					adapterRow.clear();
					rowItems.clear();
				}
				dbHelper.getItemSummaryList(list, type, null);
				rowItems = list;
				
				
				if (rowItems != null && rowItems.size() != 0) {
					for (int i = 0; i < rowItems.size(); i++) {
						adapterRow.add(rowItems.get(i));
					}
					adapter = new CustomListViewAdapter(
							DeliveryListActivity.this,
							R.layout.list_item_actives, adapterRow);
					mCustomViewListAdapter = adapter;
					
				} else {
					toast("DB is empty please save tracks first");
				}
			} else {
				toast("Please Import tracking DB from Memory");
			}

			trackListView.setAdapter(mCustomViewListAdapter);

			trackListView.setOnItemClickListener(this);
			trackListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					openDetailsFragment(position, type);
				}
			});
		} else if (type.equalsIgnoreCase("Category")) {
			ApplicationVars localObj = ApplicationVars.getInstance();
			if (firstCall) {
			    localObj.setTrackList(new ArrayList<RowItem>());
			}
			ArrayList<RowItem> list = localObj.getTrackList();
			RelsellDBOpenHelper dbHelper = new RelsellDBOpenHelper(this);
			CustomListViewAdapter adapter = null;
			if (dbHelper.checkDBPresence(this)) {
				if(adapterRow != null && rowItems != null) {
					adapterRow.clear();
					rowItems.clear();
				}
				dbHelper.getItemSummaryList(list, type, categoryName);
				rowItems = list;
				if(ApplicationVars.getInstance().getTempListAfterRefresh() != null){
					rowItems = ApplicationVars.getInstance().getTempListAfterRefresh();
				}
				if (rowItems != null && rowItems.size() != 0) {
					for (int i = 0; i < rowItems.size(); i++) {
						adapterRow.add(rowItems.get(i));
					}
					adapter = new CustomListViewAdapter(
							DeliveryListActivity.this,
							R.layout.list_item_actives, adapterRow);
					mCustomViewListAdapter = adapter;
				} else {
					toast("DB is empty please save tracks first");
				}
			} else {
				toast("Please Import tracking DB from Memory");
			}

			trackListView.setAdapter(mCustomViewListAdapter);

			trackListView.setOnItemClickListener(this);
			trackListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					openDetailsFragment(position, type);
				}
			});
		} else if (type.equalsIgnoreCase("Completed")) {
			ApplicationVars localObj = ApplicationVars.getInstance();
			localObj.setCompletedTrackList(new ArrayList<RowItem>());
			ArrayList<RowItem> list = localObj.getCompletedTrackList();
			RelsellDBOpenHelper dbHelper = new RelsellDBOpenHelper(this);
			CustomListViewAdapter adapter = null;
			if (dbHelper.checkDBPresence(this)) {
				if(adapterRow != null && rowItems != null) {
					adapterRow.clear();
					rowItems.clear();
				}
				dbHelper.getItemSummaryList(list, type, null);
				rowItems = list;
				if(ApplicationVars.getInstance().getTempListAfterRefresh() != null){
					rowItems = ApplicationVars.getInstance().getTempListAfterRefresh();
				}
				if (rowItems != null && rowItems.size() != 0) {
					for (int i = 0; i < rowItems.size(); i++) {
						adapterRow.add(rowItems.get(i));
					}
					adapter = new CustomListViewAdapter(
							DeliveryListActivity.this,
							R.layout.list_item_actives, adapterRow);
					mCustomViewListAdapter = adapter;
				} else {
					toast("DB is empty please save tracks first");
				}
			} else {
				toast("Please Import tracking DB from Memory");
			}

			trackListView.setAdapter(mCustomViewListAdapter);

			trackListView.setOnItemClickListener(this);
			trackListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					openDetailsFragment(position, type);
				}
			});
		}
	}

	private void openDetailsFragment(int position, String type) {
		detailFragmentOpen = true;
		ApplicationVars.getInstance().setDetailFragmentOpen(detailFragmentOpen);
		mListLayout.setVisibility(View.GONE);
		FragmentManager fm = getSupportFragmentManager();
		fwb = new TrackDetailsFragment();
		RowItem item = (RowItem) trackListView.getItemAtPosition(position);
		selectedItemId = item.itemSummary._id;
		Bundle args = new Bundle();
		args.putString(TrackDetailsFragment.ARG_POSITION_TRACK, selectedItemId);
		args.putString(TrackDetailsFragment.ARG_TYPE, type);
		args.putString(TrackDetailsFragment.CATEGORY, categoryName);
		fwb.setArguments(args);
		FragmentTransaction ft = fm.beginTransaction();
		ft.replace(R.id.frameid_container, fwb);
		ft.commit();
	}

	@Override
	protected void onStart() {
		Intent intent = getIntent();
		int x = intent.getIntExtra("value", 0);
		// x==0 means forward transition and else means backward transition
		if (x == 0) {
			Log.e("TAG", "" + x);
			overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
		}
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_list, menu);
		
		
		
		SearchView searchView = (SearchView) menu.findItem(R.id.nav_serach)
				.getActionView();
		if (searchView == null) {
			toast("null");
		}
		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {

				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				// setUpList(newText);
				return false;
			}
		});
		searchView.setOnCloseListener(new OnCloseListener() {

			@Override
			public boolean onClose() {
				// toast("closed");
				// copyFullList();
				// adapter.notifyDataSetChanged();
				return false;
			}
		});

		return super.onCreateOptionsMenu(menu);
	}

	protected boolean isAlwaysExpanded() {
		return false;
	}

	private void setUpList(String query) {

		String des, track;
		query = query.toLowerCase();
		int i;
		adapterList.clear();
		for (i = 0; i < list.size(); i++) {
			des = list.get(i).getDescription().toLowerCase();
			track = list.get(i).getId().toLowerCase();
			if (des.contains(query))
				adapterList.add(list.get(i));
			if (track.contains(query))
				adapterList.add(list.get(i));

		}
		adapter.notifyDataSetChanged();

	}

	private void copyFullList() {
		int i;
		adapterList.clear();
		for (i = 0; i < list.size(); i++) {
			adapterList.add(list.get(i));
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			if (detailFragmentOpen) {
				mListLayout.setVisibility(View.VISIBLE);
				FragmentManager fm = getSupportFragmentManager();
				FragmentTransaction ft = fm.beginTransaction();
				fwb.setHasOptionsMenu(false);
				actionbar.setTitle(type);
				if (categoryName != null) {
					actionbar.setTitle(categoryName);
				}
				ft.hide(fwb);
				detailFragmentOpen = false;
				ApplicationVars.getInstance().setDetailFragmentOpen(false);
			} else {
				detailFragmentOpen = false;
				ApplicationVars.getInstance().setDetailFragmentOpen(false);
				moveBack();
			}
			return true;
		} else if (item.getItemId() == R.id.nav_add) {
			showAddDialog();
			return true;
		} else if (item.getItemId() == R.id.exit) {

			showExitDialog();
		} else if (item.getItemId() == R.id.action_settings) {

			Intent intentHome = new Intent(getApplicationContext(),
					SettingsActivity2.class);
			intentHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentHome.putExtra("contenttype", type);
			startActivity(intentHome);
			return true;
		} else if (item.getItemId() == R.id.about) {
			// ShowAboutDiallog();
			Intent intentHome = new Intent(getApplicationContext(),
					AboutActivity.class);
			intentHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentHome.putExtra("contenttype", type);
			startActivity(intentHome);
			return true;
		} else if (item.getItemId() == R.id.nav_refresh) {
			Intent serviceIntent = new Intent(DeliveryListActivity.this,
					TrackerServiceClass.class);
			mSharedpreferences = getSharedPreferences(TrackerServiceClass.TRACKPREFERENCES,
					Context.MODE_PRIVATE);
			Editor editor = mSharedpreferences.edit();
			editor.putString("caller","0");
			editor.putBoolean("bulkcaller",!ApplicationVars.getInstance().isDetailFragmentOpen());
			editor.putString("idForTrack",selectedItemId);
			editor.commit();
			serviceIntent.putExtra("type",type);
			serviceIntent.putExtra("categoryName",categoryName);
			startService(serviceIntent);
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void setSearchDialog() {

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.action_bar_serach, null);
		actionbar.setCustomView(v);

	}

	private void exit() {

		Intent intent = new Intent(this, DemoActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_CLEAR_TASK
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		finish();
	}

	private void showAddDialog() {
		final Dialog dialog = new Dialog(DeliveryListActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.addcontent);
		final EditText edtPkgNumber = (EditText) dialog
				.findViewById(R.id.editText1);
		final EditText edtPkgDescription = (EditText) dialog
				.findViewById(R.id.editText2);
		final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner1);
		setSpinnerItem();
		SpinnerItemAdapter adapter = new SpinnerItemAdapter(
				getApplicationContext(), R.layout.spinner_row_view_custom,
				spinnerItem);
		spinner.setAdapter(adapter);

		Button btnOk = (Button) dialog.findViewById(R.id.button2);
		Button btnCancel = (Button) dialog.findViewById(R.id.button1);
		btnOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String tracknumber = edtPkgNumber.getText().toString();
				String description = edtPkgDescription.getText().toString();
				String category = spinner.getSelectedItem().toString();
				String status = "NOT DELIVERED";
				if (!tracknumber.equals("") && !description.equals("")
						&& !category.equals("")) {
					if (ApplicationVars.getInstance().isSubscribed()) {
						RelsellDBOpenHelper dbHelper = new RelsellDBOpenHelper(
								DeliveryListActivity.this);
						dbHelper.openDb();
						int res = dbHelper.saveDelivery(description,
								tracknumber, category, status);
						if (res == 1) {
							
						    if(adapterRow != null) {
									adapterRow.add(new RowItem(tracknumber,category,status,null,null,"-10001","0",description));
							}
							if (mCustomViewListAdapter != null) {
								mCustomViewListAdapter.notifyDataSetChanged();
							}
							

							Intent intent= new Intent(DeliveryListActivity.this,DeliveryListActivity.class);
							intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							intent.putExtra("type","Active");
							startActivity(intent);
						} else {
							toast("subcription limit is reached");
						}
					} else {
						//ApplicationVars.getInstance().getSubscriptionObject()
						//		.setSubscrtionTypeInteger(30);
						toast("subcription required to save more tracks");
					}

					dialog.dismiss();

				} else
					toast("Some fields are empty");

			}
		});
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private void setSpinnerItem() {
		spinnerItem.add("None");
		spinnerItem.add("Incoming");
		spinnerItem.add("Outgoing");
		spinnerItem.add("Favorite");
		spinnerItem.add("Important");
		spinnerItem.add("Movie");
		spinnerItem.add("Gift");
		spinnerItem.add("Heart");
		spinnerItem.add("Business");
		spinnerItem.add("Camera");
		spinnerItem.add("Clothes");
		spinnerItem.add("Computer");
		spinnerItem.add("Games");
		spinnerItem.add("Food Dishes");
		spinnerItem.add("Light");
		spinnerItem.add("Music");
		spinnerItem.add("Office Materials");
		spinnerItem.add("Paint");
		spinnerItem.add("Medicine");
		spinnerItem.add("Flowers");
		spinnerItem.add("Sports");
		spinnerItem.add("Tools");
	}

	private void toast(String str) {
		Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
	}

	private void showExitDialog() {

		AlertDialog Alert = new AlertDialog.Builder(DeliveryListActivity.this)
				.create();
		Alert.setTitle("Exit");
		Alert.setMessage("Want to close?");

		Alert.setButton(BUTTON_POSITIVE, "Exit",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						exit();
						dialog.dismiss();
						// to do
					}
				});

		Alert.setButton(BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();

					}
				});
		Alert.show();
	}

	private void ShowAboutDiallog() {
		final Dialog dialog = new Dialog(DeliveryListActivity.this);

		dialog.setContentView(R.layout.dialog_about);
		dialog.setTitle("About:Track My Packages");
		TextView txtNotNow = (TextView) dialog.findViewById(R.id.textView5);
		TextView textrate = (TextView) dialog.findViewById(R.id.textView4);
		Spannable txtlabel = new SpannableString(
				"Rate Track My Packages on   Google Play");
		// Bitmap smiley = BitmapFactory.decodeResource( getResources(),
		// R.drawable.play);
		txtlabel.setSpan(
				new ImageSpan(getApplicationContext(), R.drawable.play), 26,
				27, 0);
		textrate.setText(txtlabel);
		textrate.setGravity(Gravity.TOP);
		txtNotNow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();

			}
		});
		dialog.show();
	}

	private void moveBack() {
		Intent intentHome = new Intent(getApplicationContext(),
				MainActivity.class);
		intentHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intentHome);
		overridePendingTransition(R.anim.anim_in_left, R.anim.anim_out_left);

	}

	@Override
	public void onBackPressed() {
		moveBack();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}


	@Override
	public void updateUIForList(HashMap<String,String> trackIdAndStatus) {
		
		String trackinId = trackIdAndStatus.get("trackingid");
		String origin = trackIdAndStatus.get("origin");
		String dest = trackIdAndStatus.get("destination");
		String status = trackIdAndStatus.get("status");
		
			if(adapterRow != null) {
				for(RowItem localRowItem : adapterRow) {
					if(localRowItem.itemSummary._id.equalsIgnoreCase(trackinId)) {
						localRowItem.itemSummary.status = status;
						localRowItem.itemSummary.origin = origin;
						localRowItem.itemSummary.destination = dest;
					}
				}
			}
		
		mCustomViewListAdapter.notifyDataSetChanged();
	}
}
